//
//  BonjourSensor.m
//  Pennyworth
//
//  Created by Chris Karr on 12/24/07.
//  Copyright 2007 Chris J. Karr. All rights reserved.
//

#import "BonjourSensor.h"
#import "Context.h"
#import "SensorsController.h"

#define SENSOR_NAME @"Bonjour Services"

@implementation BonjourSensor

- (void) awakeFromNib
{
	[[SensorsController sharedController] addSensor:SENSOR_NAME];
	
	search = [[NSNetServiceBrowser alloc] init];
	services = [[NSMutableArray alloc] init];
	foundServices = [[NSMutableArray alloc] init];
		
	searching = NO;
		
	[search setDelegate:self];

	timer = [[NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(update:) userInfo:nil repeats:YES] retain];
	[timer fire];

}

- (void) update:(NSTimer *) theTimer
{
	if (![[SensorsController sharedController] canFire:SENSOR_NAME])
	{
		NSMutableDictionary * note = [NSMutableDictionary dictionary];
		[note setValue:SENSOR_NAME forKey:OBSERVATION_SENSOR];
		[[NSNotificationCenter defaultCenter] postNotificationName:OBSERVATION_UPDATE object:self userInfo:note];
		
		return;
	}		
	
	if (searching)
		return;
		
	searching = YES;
	
	[foundServices release];
	foundServices = [[NSMutableArray alloc] init];
	
	[services removeAllObjects];
	
	[search searchForServicesOfType:@"_services._dns-sd._udp." inDomain:@""];
}

- (void) netServiceBrowser:(NSNetServiceBrowser *) netServiceBrowser didFindService:(NSNetService *) netService 
	moreComing:(BOOL) moreServicesComing
{
	if (![[netService name] isEqual:@"_net-assistant"] && ![[netService name] hasPrefix:@"_zuul"])
	{
		if ([netService hostName] == nil && [[netService name] hasPrefix:@"_"])
			[services addObject:[netService name]];
		else
		{
			NSString * serviceString = [NSString stringWithFormat:@"%@ (%@)", [netService name], [netService type]];

			if (![foundServices containsObject:serviceString])
				[foundServices addObject:serviceString];
		}
	}
	
	if (!moreServicesComing)
	{
		[netServiceBrowser stop];

		if ([services count] > 0)
		{
			NSString * type = [[services objectAtIndex:0] retain];
			[services removeObject:type];

			type = [type stringByAppendingString:@"._tcp."];
		
			[search searchForServicesOfType:type inDomain:@""];
		}
		else
		{
			searching = NO;
			
			NSMutableDictionary * note = [NSMutableDictionary dictionary];
			[note setValue:@"Bonjour Services" forKey:OBSERVATION_SENSOR];
			[note setValue:foundServices forKey:OBSERVATION_OBSERVATION];
			[[NSNotificationCenter defaultCenter] postNotificationName:OBSERVATION_UPDATE object:self userInfo:note];
		}
	}
}

/* - (void)netServiceBrowser:(NSNetServiceBrowser *)netServiceBrowser didNotSearch:(NSDictionary *)errorInfo
{
	NSLog (@"error: %@", errorInfo);
} */

@end
